﻿$(function() {
    initReportTable();
});

function initReportTable() {
    if ($('select#month').length > 0) $('select#month').change(function() { $(this).find('option').each(function() { if ($(this).attr('selected')) changeMonth($(this).val(), true); }); });
    if ($('select#year').length > 0) $('select#year').change(function() { $(this).find('option').each(function() { if ($(this).attr('selected')) changeYear($(this).val(), true); }); });

    $('form#productionform table.data a').click(function() {
        var form = $('form:first');
        var params = { timestamp: new Date(), nolayout: true, startdate: $('#startdate').val(), enddate: $('#enddate').val(), sortorder: $(this).attr('id') };
        $('#wrapper').load(base + form.attr('action'), params, function() { initReportTable();  $('input.dateRU').calendar({ dateFormat: '%d.%m.%Y' }); });
        return false;
    });
	/*
	var sortorder = $('#sortorder').val();
	$('form#productionform table.data a').each(function() {
		var a = $(this);
		if (a.attr('id') == sortorder)
			a.addClass('sorted');
    });*/
}

function changeMonth(month, onchange) {
	changeDateMonth(month, $('#startdate'), true);
	changeDateMonth(month, $('#enddate'), false);
	if (onchange)
	    changeYear($('select#year option[selected=true]:first').val(), false);
	return false;
}

function changeYear(year, onchange) {
	changeDateYear(year, $('#startdate'));
	changeDateYear(year, $('#enddate'));
	if (onchange)
	    changeMonth($('select#month option[selected=true]:first').val(), false);
	return false;
} 

function changeDateMonth(month, input, isStartDate) {
    var date = $.parseDate(input.val());
    var year = date.getFullYear();
    date = new Date(year, month-1, (isStartDate) ? 1 : daysInMonth(month, year));
    input.val($.getDateString(date));
    return false;  
}

function changeDateYear(year, input) {
    var date = $.parseDate(input.val());
    date.setYear(year);
    input.val($.getDateString(date));
    return false;  
}

function daysInMonth(month,year) {
	var dd = new Date(year, month, 0);
	return dd.getDate();
}

function exportExcel() {
	params = $('form').serialize();
	var tableController = $('#tablecontroller').val() + '.ivp/';
    window.open(base + tableController + 'excel?' + params);
    return false;
}
